package src.数据结构.映射;

public class SymbolTable<Key, Value> {
    // 无序键值对
    private Node head;
    private int N;

    public SymbolTable() {
        this.head = null;
        this.N = 0;
    }

    public Value get(Key key) {
        Node<Key, Value> n = this.head;
        if (n == null) {
            return null;
        } else {
            while (n.next != null) {
                if (n.key.equals(key)) {
                    return n.value;
                }
                n = n.next;
            }
        }
        return null;
    }

    public void put(Key key, Value value) {
        // key 存在则替换值
        Node n = this.head;
        while (n != null) {
            if (n.key.equals(key)) {
                n.value = value;
                return;
            }
            n = n.next;
        }

        // key 不存在则创建新节点并插入到表头
        Node<Key, Value> newNode = new Node<>(key, value, null);

          /*
        倒序插入
        Node oldHead = head;
        newNode.next = oldHead;
        head = newNode;*/

        // 顺序插入
        if (this.head == null) {
            this.head = newNode;
        } else {
            n = this.head;
            while (n.next != null) {
                n = n.next;
            }
            n.next = newNode;
        }
        this.N++;
    }

    public void delete(Key key) {
        // 处理头节点的特殊情况
        if (this.head != null && this.head.key.equals(key)) {
            // 删除头节点并更新头节点
            this.head = this.head.next;
            this.N--;
            return;
        }

        Node n = this.head;
        while (n != null && n.next != null) {
            if (n.next.key.equals(key)) {
                n.next = n.next.next;
                this.N--;
                return;
            }
            n = n.next;
        }
    }

    public int size() {
        return this.N;
    }

    public void show() {
        Node n = head;
        while (n != null) {
            System.out.print(n.key + ":" + n.value + " ");
            n = n.next;
        }
        System.out.println();
    }
}
